/*
============== Quantumult X 配置块 ==============
[rewrite_local]
# 密钥捕获规则
^https?:\/\/floor\.huluxia\.com\/(user\/\w+|account\/info)\/IOS\/1\.\d+ url script-request-body https://gitee.com/juebi01/hlxzdqd/raw/master/hl.js

# 签到结果美化
^https?:\/\/floor\.huluxia\.com\/user\/signin\/IOS\/1\.1 url script-response-body https://gitee.com/juebi01/hlxzdqd/raw/master/hl.js

[mitm]
hostname = floor.huluxia.com, *.huluxia.com

[task_local]
# 每日7点自动执行
0 7 * * * https://gitee.com/juebi01/hlxzdqd/raw/master/hl.js, tag=葫芦侠全自动签到, enabled=true
============== 配置结束 ==============
*/

// ================== 优化版脚本核心代码 ==================
const CONFIG = {
  STORAGE_KEY: 'huluxia_auth_v7',
  BASE_URL: 'https://floor.huluxia.com',
  DELAY: 2500,  // 签到间隔
  RETRY_DELAY: 5000, // 重试延迟
  MAX_RETRY: 2, // 最大重试次数
  VERSION: '7.0',
  
  // 所有需要签到的板块ID
  CATEGORY_LIST: [1, 2, 3, 4, 6, 15, 16, 21, 22, 29, 43, 44, 45, 57, 58, 60, 63, 67, 68, 69, 70, 71, 76, 81, 82, 84, 92, 94, 96, 98, 102, 108, 110, 111, 115, 119, 125, 126],
  
  // 用户代理
  USER_AGENT: "Floor/1.2.2 (iPhone; iOS 17.4; Scale/3.00)",
  
  // 密钥有效期改为7天
  KEY_EXPIRE_TIME: 7 * 24 * 3600 * 1000
};

// 🔑 密钥捕获模块
if (typeof $request !== 'undefined') {
  handleKeyCapture();
} else {
  // ✅ 自动签到模块（增强版）
  executeSignIn();
}

// 密钥捕获处理
function handleKeyCapture() {
  const { body, url, method } = $request;
  let captured = {};
  let notifyNeeded = false;
  
  try {
    // 1. 尝试JSON解析
    if (body.startsWith('{')) {
      try {
        const json = JSON.parse(body);
        if (json._key) captured._key = json._key;
        if (json.device_code) captured.device_code = json.device_code;
        if (json.user_id) captured.user_id = json.user_id;
      } catch (e) {}
    }
    
    // 2. 尝试表单解析
    if (!captured._key && body.includes('=')) {
      try {
        const params = new URLSearchParams(body);
        if (params.get('_key')) captured._key = params.get('_key');
        if (params.get('device_code')) captured.device_code = params.get('device_code');
        if (params.get('user_id')) captured.user_id = params.get('user_id');
      } catch (e) {}
    }
    
    // 3. 正则匹配
    if (!captured._key) {
      const keyMatch = body.match(/_key=([A-F0-9]{40,})/i);
      if (keyMatch && keyMatch[1]) captured._key = keyMatch[1];
    }
    
    // 4. URL参数提取
    if (!captured.user_id) {
      const userIdMatch = url.match(/user_id=(\d+)/);
      if (userIdMatch && userIdMatch[1]) captured.user_id = userIdMatch[1];
    }
    
    // 5. Cookie提取
    if (!captured._key && $request.headers && $request.headers.Cookie) {
      const cookieMatch = $request.headers.Cookie.match(/_key=([A-F0-9]{40,})/i);
      if (cookieMatch && cookieMatch[1]) captured._key = cookieMatch[1];
    }
  } catch (e) {
    console.log(`密钥捕获错误: ${e.message}`);
  }
  
  // 存储参数
  if (captured._key) {
    const existing = JSON.parse($prefs.valueForKey(CONFIG.STORAGE_KEY) || "{}");
    
    // 检查密钥是否变化
    const keyChanged = existing._key !== captured._key;
    const userIdChanged = existing.user_id !== captured.user_id;
    
    // 仅在密钥变化时通知
    if (keyChanged || userIdChanged) {
      notifyNeeded = true;
    }
    
    const merged = { 
      ...existing, 
      ...captured,
      update_time: Date.now(),
      from_url: url,
      from_method: method
    };
    
    // 确保有user_id
    if (!merged.user_id) {
      merged.user_id = "未知_" + Date.now().toString().slice(-6);
      notifyNeeded = true;
    }
    
    $prefs.setValueForKey(JSON.stringify(merged), CONFIG.STORAGE_KEY);
    
    if (notifyNeeded) {
      $notify("🔑 密钥已更新", `用户ID: ${merged.user_id}`, "有效期7天");
    }
  }
  $done({});
}

// 执行签到（增强版）
async function executeSignIn() {
  const authData = JSON.parse($prefs.valueForKey(CONFIG.STORAGE_KEY) || "{}");
  
  // 检查必要参数
  const requireKeys = ['_key'];
  const missing = requireKeys.filter(k => !authData[k]);
  if (missing.length) {
    $notify("‼️ 参数不全", `缺少密钥: _key`, "请打开APP操作");
    return $done();
  }

  // 🔄 密钥有效期检查（7天）
  if (Date.now() - (authData.update_time || 0) > CONFIG.KEY_EXPIRE_TIME) {
    $notify("🔑 密钥已过期", "请重新打开APP获取新密钥", "");
    return $done();
  }

  try {
    // 获取用户信息（新增昵称显示）
    const userInfo = await getUserInfo(authData);
    if (!userInfo) {
      $notify("❌ 获取用户信息失败", "请检查密钥是否有效", "");
      return $done();
    }
    
    const userDisplayName = `${userInfo.nick} (Lv.${userInfo.level})`;
    $notify("🎯 开始签到任务", `用户: ${userDisplayName}`, `经验: ${userInfo.exp}/${userInfo.nextExp}`);
    
    // 执行签到任务
    let successCount = 0, totalCredits = 0, totalExpGained = 0;
    let successList = [], failedList = [];
    let continueDays = 0;
    
    const totalTasks = CONFIG.CATEGORY_LIST.length;
    
    // 使用指定板块列表进行签到
    for (let i = 0; i < CONFIG.CATEGORY_LIST.length; i++) {
      const catId = CONFIG.CATEGORY_LIST[i];
      
      // 显示进度
      const progress = `[${i + 1}/${totalTasks}]`;
      console.log(`${progress} 签到板块 ${catId}...`);
      
      let retryCount = 0;
      let result = null;
      
      while (retryCount <= CONFIG.MAX_RETRY && !(result && (result.status === 1 || result.signin === 1))) {
        if (retryCount > 0) {
          console.log(`${progress} 第${retryCount}次重试...`);
          await new Promise(r => setTimeout(r, CONFIG.RETRY_DELAY));
        }
        
        result = await signSingleCategory(authData, catId);
        retryCount++;
      }
      
      if (result.status === 1 || result.signin === 1) {
        successCount++;
        totalCredits += result.credits || 0;
        totalExpGained += result.experienceVal || 0;
        successList.push(catId);
        
        // 记录连续签到天数
        if (result.continueDays) {
          continueDays = Math.max(continueDays, result.continueDays);
        }
        
        console.log(`${progress} ✅ 板块 ${catId} 签到成功`);
      } else {
        const isAlreadySigned = result.msg && result.msg.includes("已签到");
        failedList.push({
          id: catId,
          reason: isAlreadySigned ? "今日已签到" : (result.msg || '未知原因')
        });
        console.log(`${progress} ❌ 板块 ${catId} 签到失败: ${result.msg || '未知原因'}`);
      }
      
      // 板块间延迟
      if (i < CONFIG.CATEGORY_LIST.length - 1) {
        await new Promise(r => setTimeout(r, CONFIG.DELAY));
      }
    }
    
    // 重新获取用户信息以统计经验变化
    const userInfoAfter = await getUserInfo(authData);
    const actualExpGained = userInfoAfter ? (userInfoAfter.exp - userInfo.exp) : totalExpGained;
    
    // ================ 增强通知系统 ================
    const successRate = ((successCount / totalTasks) * 100).toFixed(1);
    const title = `🎉 葫芦侠签到完成 ${successRate}%`;
    const subtitle = `用户: ${userDisplayName}`;
    
    let content = `📊 签到统计:\n`;
    content += `✅ 成功: ${successCount}/${totalTasks}个板块\n`;
    content += `💰 获得积分: +${totalCredits}\n`;
    content += `📈 获得经验: +${actualExpGained}\n`;
    
    if (userInfoAfter) {
      content += `🎯 当前等级: Lv.${userInfoAfter.level}\n`;
      content += `📊 经验进度: ${userInfoAfter.exp}/${userInfoAfter.nextExp}\n`;
      
      // 计算升级所需天数（基于平均每日获得经验）
      if (actualExpGained > 0) {
        const expNeeded = userInfoAfter.nextExp - userInfoAfter.exp;
        const daysToLevelUp = Math.ceil(expNeeded / actualExpGained);
        content += `⏳ 升级预估: ${daysToLevelUp}天后\n`;
      }
    }
    
    if (continueDays > 0) {
      content += `📅 连续签到: ${continueDays}天\n`;
    }
    
    // 成功板块展示
    if (successList.length > 0) {
      content += `\n✅ 成功板块: ${successList.slice(0, 8).join(', ')}`;
      if (successList.length > 8) content += `...等${successList.length}个`;
      content += `\n`;
    }
    
    // 失败分析（如果有）
    if (failedList.length > 0) {
      const reasonCount = {};
      failedList.forEach(f => {
        reasonCount[f.reason] = (reasonCount[f.reason] || 0) + 1;
      });
      
      content += `\n❌ 失败分析:\n`;
      for (const reason in reasonCount) {
        content += `${reason}: ${reasonCount[reason]}个\n`;
      }
    }
    
    // 添加统计信息
    content += `\n🔧 脚本版本: v${CONFIG.VERSION}`;
    content += `\n⏰ 执行时间: ${new Date().toLocaleString()}`;
    
    // 发送通知
    $notify(title, subtitle, content);
    
  } catch (e) {
    $notify("‼️ 签到异常", e.message || "请检查网络和密钥状态");
  }
  $done();
}

// 获取用户信息（新增功能）
async function getUserInfo(authData) {
  try {
    const params = new URLSearchParams({
      _key: authData._key,
      user_id: authData.user_id || "unknown",
      device_code: authData.device_code || "auto_" + Date.now().toString().slice(-8),
      app_version: "1.2.2",
      market_id: "floor_huluxia",
      platform: "1"
    }).toString();

    const res = await $task.fetch({
      url: `${CONFIG.BASE_URL}/user/info/IOS/1.1`,
      method: "POST",
      headers: { 
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": CONFIG.USER_AGENT,
        "Cookie": `_key=${authData._key}`
      },
      body: params,
      timeout: 10000
    });
    
    const data = JSON.parse(res.body);
    
    if (data.status === 1) {
      return {
        nick: data.nick || '未知用户',
        identityTitle: data.identityTitle || '无',
        level: data.level || 0,
        exp: data.exp || 0,
        nextExp: data.nextExp || 0,
        credits: data.credits || 0
      };
    }
    
    return null;
  } catch (e) {
    console.log(`获取用户信息失败: ${e.message}`);
    return null;
  }
}

// 单个板块签到
async function signSingleCategory(authData, catId) {
  try {
    const payload = new URLSearchParams({
      _key: authData._key,
      device_code: authData.device_code || "auto_" + Date.now().toString().slice(-8),
      user_id: authData.user_id || "unknown",
      app_version: "1.2.2",
      cat_id: catId,
      market_id: "floor_huluxia",
      platform: "1"
    }).toString();

    const res = await $task.fetch({
      url: `${CONFIG.BASE_URL}/user/signin/IOS/1.1`,
      method: "POST",
      headers: { 
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": CONFIG.USER_AGENT,
        "Cookie": `_key=${authData._key}`
      },
      body: payload,
      timeout: 15000
    });
    
    const result = JSON.parse(res.body);
    
    // 特殊处理"今日已签到"情况
    if (result.status === 0 && result.msg && result.msg.includes("已签到")) {
      return { status: 1, credits: 0, experienceVal: 0, msg: "今日已签到" };
    }
    
    return result;
  } catch (e) {
    return { status: 0, msg: `请求失败: ${e.message}` };
  }
}
